package com.sxz.sbs.module.client;

import android.Manifest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.event.RecoverDetailPhoneEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.adapter.CallRecordsAdapter;
import com.sxz.sbs.module.client.bean.CallBean;
import com.sxz.sbs.module.client.bean.CallRecordsBean;
import com.sxz.sbs.module.client.bean.ClientDetailsBean;
import com.sxz.sbs.module.client.presenter.CallRecordsPresenter;
import com.sxz.sbs.module.client.view.CallRecordsView;
import com.sxz.sbs.widget.CommonTitle;
import com.sxz.sbs.widget.MultiplePhoneDialog;
import com.sxz.sbs.widget.StallAlertDialog;
import com.willy.ratingbar.ScaleRatingBar;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.telephony.TelephonyManager.CALL_STATE_IDLE;

/**
 * @author hp
 * @date 2018/1/12
 * 通话记录
 */

public class CallRecordsActivity extends BaseActivity<CallRecordsPresenter> implements CallRecordsView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.stateLayout)
    StateLayout stateLayout;
    @BindView(R.id.simpleRatingBar)
    ScaleRatingBar simpleRatingBar;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_state)
    TextView tvState;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    private CallRecordsAdapter callRecordsAdapter;
    private ClientDetailsBean mdata;
    private List<CallRecordsBean> dataList = new ArrayList<>();
    private String callPhone = "";
    private Intent phoneIntent;
    private BroadcastReceiver callReceiver;
    private TelephonyManager tm;
    private boolean isCall;
    private String endTime = "";
    @Override
    protected void init() {
        mdata = getIntent().getParcelableExtra("client_detail_bean");
        new CommonTitle.Builder(this).setTitle("通话记录").build().show();
        callReceiver = new CallReceiver();
        IntentFilter intentFilter = new IntentFilter("call_action");
        registerReceiver(callReceiver,intentFilter);
        if (mdata != null) {
            tv_name.setText(mdata.getTxt_UserName());
            tvAddress.setText(mdata.getAddr_Address());
            if (!TextUtils.isEmpty(mdata.getTxt_Phone())) {
                tv_phone.setText(mdata.getTxt_Phone().split(",")[0]);
            }
            if (mdata.getVal_StarLevel() <= 0) {
                simpleRatingBar.setVisibility(View.GONE);
            } else {
                simpleRatingBar.setVisibility(View.VISIBLE);
                simpleRatingBar.setNumStars(mdata.getVal_StarLevel());
                simpleRatingBar.setRating(mdata.getVal_StarLevel());
            }
            tvState.setText(mdata.getDisplayStatus());
            getCallRecordsData();
        }
        callRecordsAdapter = new CallRecordsAdapter(dataList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(callRecordsAdapter);
        stateLayout.setOnRetryListener(new StateLayout.OnRetryListener() {
            @Override
            public void onRetry(int state) {
                getCallRecordsData();
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_callrecords;
    }

    @Override
    protected CallRecordsPresenter createPresenter() {
        return new CallRecordsPresenter();
    }

    /**
     * 员工客户通话记录
     */

    private void getCallRecordsData() {
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", mdata.getId());
        mPresenter.getCallRecords(map);
    }

    @Override
    public void showError(int errorTag, String msg) {
        if (errorTag == AppConstant.NET_ERROR_CODE) {
            stateLayout.showNetwork();
        } else {
            stateLayout.showEmpty();
        }

    }

    @Override
    public void onCallRecordsSuccess(List<CallRecordsBean> data) {
        if (mIsLive) {
            if (data != null && data.size() > 0) {
                stateLayout.showContent();
                dataList.clear();
                dataList.addAll(data);
                callRecordsAdapter.notifyDataSetChanged();
            } else {
                stateLayout.showEmpty();
            }
        }
    }

    @Override
    public void onAddIntentionClientSuccess(String data) {
        ToastUtils.showShort("添加成功,请到意向客户列表里查看");
    }

    @Override
    public void onAddCallRecordSuccess() {
        getCallRecordsData();
    }

    @OnClick(R.id.ivCall)
    public void onViewClicked() {
        if (mdata == null) return;
        PermissionUtils.permission("android.permission.CALL_PHONE","android.permission.READ_CALL_LOG").callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                if (!TextUtils.isEmpty(mdata.getTxt_Phone())) {
                    String[] phoneArr = mdata.getTxt_Phone().split("\\,");

                    if (phoneArr.length <= 0) {
                        ToastUtils.showShort("无手机号");
                        return;
                    }
                    if (phoneArr.length > 0 && phoneArr.length <= 1 ) {
                        if (!TextUtils.isEmpty(phoneArr[0])) {
                            callPhone = phoneArr[0];
                            new StallAlertDialog.Builder(CallRecordsActivity.this)
                                    .showTitle(false)
                                    .setMessage(callPhone)
                                    .setPositiveButton("呼叫", new StallAlertDialog.OnPositiveListener() {
                                        @Override
                                        public void onPositiveClick(View view) {
                                            phoneIntent = new Intent("call_action");
                                            sendBroadcast(phoneIntent);
                                            Intent intent = new Intent();
                                            intent.setAction(Intent.ACTION_CALL);
                                            intent.setData(Uri.parse("tel:" + callPhone));
                                            startActivity(intent);

                                        }
                                    }).create().show();
                        }else {
                            ToastUtils.showShort("无手机号");
                        }
                    } else if (phoneArr.length > 1){
                        List<String> phones = new ArrayList<String>();
                        for (int i = 0; i < phoneArr.length; i++) {
                            if (!TextUtils.isEmpty(phoneArr[i])) {
                                phones.add(phoneArr[i]);
                            }
                        }
                        MultiplePhoneDialog dialog = new MultiplePhoneDialog(CallRecordsActivity.this,phones);
                        dialog.setOnChosePhoneListener(new MultiplePhoneDialog.OnChosePhoneListener() {
                            @Override
                            public void onSelectPhone(String phone) {
                                callPhone =  phone;
                                phoneIntent = new Intent("call_action");
                                sendBroadcast(phoneIntent);
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_CALL);
                                intent.setData(Uri.parse("tel:" + callPhone));
                                startActivity(intent);
                            }
                        });
                        dialog.show();
                    }
                } else {
                    ToastUtils.showShort("无手机号");
                }
            }
            @Override
            public void onDenied() {
                ToastUtils.showShort("请授予打电话和读取通话记录权限");
            }
        }).request();
    }
    private class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("action" + intent.getAction());
            //如果是去电
            if (!intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
                tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
            }
        }
    }
    private PhoneStateListener listener=new PhoneStateListener(){
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //注意，方法必须写在super方法后面，否则incomingNumber无法获取到值。
            super.onCallStateChanged(state, incomingNumber);
            switch(state){
                case CALL_STATE_IDLE:
                    if (isCall) {
                        isCall = false;
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        getCallRecord();
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    isCall = true;
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    break;
                default:
                    break;
            }
        }
    };
    private void getCallRecord() {
        ContentResolver resolver = getContentResolver();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI,
                new String[]{CallLog.Calls.CACHED_NAME
                        , CallLog.Calls.NUMBER
                        , CallLog.Calls.DATE
                        , CallLog.Calls.DURATION
                        , CallLog.Calls.TYPE}
                , CallLog.Calls.NUMBER + "=" + callPhone, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        // 3.通过Cursor获得数据
        List<CallBean> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
            String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
            long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
            int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
            int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
            String typeString = "";
            switch (type) {
                case CallLog.Calls.INCOMING_TYPE:
                    typeString = "打入";
                    break;
                case CallLog.Calls.OUTGOING_TYPE:
                    typeString = "打出";
                    break;
                case CallLog.Calls.MISSED_TYPE:
                    typeString = "未接";
                    break;
                default:
                    break;
            }
            CallBean callBean = new CallBean();
            callBean.setName((name == null) ? "未备注联系人" : name);
            callBean.setNumber(number);
            callBean.setDate(date);
            callBean.setDuration(duration);
            callBean.setType(typeString);
            list.add(callBean);
        }
        cursor.close();

        if(list != null && list.size() > 0) {
            //  查询出了数据
            final CallBean callBean = list.get(0);
            if (callBean.getDuration() > 0 ) {
                /*if (txt_Para.equals("valType=1&valStatus=0")) {
                    UpdateRecordDialog dialog = new UpdateRecordDialog(this);
                    dialog.setOnUpdateDialogListener(new UpdateRecordDialog.OnUpdateDialogListener() {
                        @Override
                        public void onClose(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                        }
                        @Override
                        public void onToIntent(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                            HashMap<String, Object> map = HttpParamMap.getParamMap();
                            map.put("customId", mdata.getId());
                            map.put("valType", TypeConstant.VAL_TYPE_HAVE);
                            mPresenter.getAddIntentionClient(map);
                        }

                        @Override
                        public void onToUpdate(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                            Intent intent=new Intent(ClientDetailsActivity.this,ClientEvaluateActivity.class);
                            intent.putExtra("clientid",mdata.getId());
                            intent.putExtra("starnum",mdata.getVal_StarLevel());
                            startActivity(intent);
                        }
                    });
                    dialog.show();
                } else {*/
                addCallRecord(callBean);
                //}


            }

        }

    }
    /**
     * 新增通话记录
     */
    private void addCallRecord(CallBean callBean) {
        endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        HashMap<String,Object> map = HttpParamMap.getParamMap();
        map.put("customId",mdata.getId());
        map.put("callBeginTime",callBean.getDate());
        map.put("callEndTime",endTime);
        mPresenter.addCallRecord(map);

    }
    @Override
    protected void onDestroy() {
        EventBus.getDefault().post(new RecoverDetailPhoneEvent());
        if (tm != null) {
            tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        }
        unregisterReceiver(callReceiver);
        super.onDestroy();

    }
}
